package ernie.server.context;

import java.io.IOException;
import java.util.List;

import misc.JSONStringStream;
import net.sourceforge.javajson.JsonArray;
import stock.Sale;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

import ernie.database.Database;
import ernie.server.ParameterParser;
import net.sourceforge.javajson.JsonObject;

/**
 * @author Filip Lindqvist <buggfille@gmail.com>
 * @created 7:04:04 PM - Nov 24, 2011 Uses
 */
public class JSONresponse implements HttpHandler {
    private final Database db;

    public JSONresponse(Database db) {
        this.db = db;
    }

    @Override
    public void handle(HttpExchange he) throws IOException {
        ParameterParser parser = new ParameterParser(he.getRequestURI());
        String target = parser.parseQuery().get("target");
        List<Sale> sales = db.loadEntries(0, target);
        JsonArray arr = new JsonArray();
        for (Sale sale : sales) {
            JsonObject object = new JsonObject();
            sale.putJSON(object);
            arr.add(object);
        }
        JSONStringStream stream = new JSONStringStream(he);
        stream.write(arr);
        stream.close();
    }

}
